package com.tebiecloud.store.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.tebiecloud.common.model.PageResult;
import com.tebiecloud.common.utils.DistanceUtils;
import com.tebiecloud.common.utils.RedisUtils;
import com.tebiecloud.common.utils.StringUtils;
import com.tebiecloud.common.utils.UUIDUtil;
import com.tebiecloud.store.client.constatns.StoreConstants;
import com.tebiecloud.store.client.model.entity.Store;
import com.tebiecloud.store.client.model.entity.StoreBankCard;
import com.tebiecloud.store.client.model.entity.StoreProfession;
import com.tebiecloud.store.client.model.entity.StoreStaff;
import com.tebiecloud.store.client.model.vo.StoreVO;
import com.tebiecloud.store.client.model.vo.WithdrawInfoVO;
import com.tebiecloud.store.server.mapper.StoreBankCardMapper;
import com.tebiecloud.store.server.mapper.StoreMapper;
import com.tebiecloud.store.server.mapper.StoreProfessionMapper;
import com.tebiecloud.store.server.mapper.StoreStaffMapper;
import com.tebiecloud.store.server.service.StoreService;
import com.tebiecloud.common.mybatis.base.service.impl.BaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 门店表 服务实现类
 *
 * @author tebie
 * @date 2019-09-15
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class StoreServiceImpl extends BaseServiceImpl<StoreMapper, Store> implements StoreService {

    @Autowired
    StoreMapper storeMapper;

    @Autowired
    StoreBankCardMapper storeBankCardMapper;

    @Autowired
    StoreProfessionMapper storeProfessionMapper;

    @Autowired
    StoreStaffMapper storeStaffMapper;

    @Autowired
    RedisUtils redisUtils;

    @Override
    public StoreVO info(Long storeId) {
        QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        Store store = storeMapper.selectOne(queryWrapper);
        StoreVO storeVO = new StoreVO();
        storeVO.setAddress(store.getAddress());
        storeVO.setLat(store.getLat());
        storeVO.setLng(store.getLng());
        String[] milieuPics = store.getMilieuPic().split(",");
        storeVO.setMilieuPic(Arrays.asList(milieuPics));
        storeVO.setOpenEtime(store.getOpenEtime());
        storeVO.setOpenStime(store.getOpenStime());
        storeVO.setStoreName(store.getName());
        storeVO.setStorePhone(store.getStorePhone());
        storeVO.setStoreId(store.getStoreId());
        storeVO.setBalance(store.getBalance()==null?0:store.getBalance());
        return storeVO;
    }

    @Override
    public List<StoreVO> listNearby(Double lng, Double lat,List<String> storeIds) {
        List<StoreVO> storeVOList = null;
        if(lat!=null && lng!=null && lat!=-1 && lng!=-1){
            storeVOList = storeMapper.selectNearby(lng, lat,storeIds);
            for (StoreVO storeVO : storeVOList) {
                String distance = DistanceUtils.getDistance(lng,lat,storeVO.getLng(),storeVO.getLat());
                storeVO.setDistance(distance);
            }
        }else{
            storeVOList = new ArrayList<>();
            QueryWrapper<Store> storeQueryWrapper = new QueryWrapper<>();
            if(storeIds!=null && storeIds.size()>0){
                storeQueryWrapper.in("store_id",storeIds);
            }
            storeQueryWrapper.orderByDesc("ct");
            List<Store> stroreList = storeMapper.selectList(storeQueryWrapper);
            if(stroreList!=null && stroreList.size()>0){
                for(Store store:stroreList){
                    StoreVO storeVO = new StoreVO();
                    storeVO.setStoreId(store.getStoreId());
                    storeVO.setStorePhone(store.getStorePhone());
                    storeVO.setStoreName(store.getName());
                    storeVO.setOpenStime(store.getOpenStime());
                    storeVO.setOpenEtime(store.getOpenEtime());
                    storeVO.setLng(store.getLng());
                    storeVO.setLat(store.getLat());
                    storeVO.setAddress(store.getAddress());
                    storeVO.setDistance("");
                    storeVOList.add(storeVO);
                }
            }
        }
        return storeVOList;
    }

    @Override
    public Store updateBalance(long storeId, int balance) {
        int time = 10;
        String key = StoreConstants.REDIS_BALANCE_+storeId;
        Boolean isLock = redisUtils.lock(key,time);
        if(!isLock){
            throw new RuntimeException("资金池被占用，请稍等");
        }
        //查询钱包
        QueryWrapper<Store> storeQueryWrapper = new QueryWrapper<>();
        storeQueryWrapper.eq("store_id",storeId);
        Store store = storeMapper.selectOne(storeQueryWrapper);
        if(store != null){
            int oldBalance = store.getBalance()==null?0:store.getBalance();
            Store newStore = new Store();
            newStore.setBalance(oldBalance+balance);
            UpdateWrapper<Store> storeUpdateWrapper = new UpdateWrapper<>();
            storeUpdateWrapper.eq("store_id",storeId);
            storeMapper.update(newStore,storeUpdateWrapper);
            store.setBalance(oldBalance+balance);
        }
        //解锁
        redisUtils.unLock(key);
        return store;
    }

    @Override
    public WithdrawInfoVO infoWithdraw(long storeId) {
        WithdrawInfoVO withdrawInfoVO = new WithdrawInfoVO();
        //获取银行卡信息
        QueryWrapper<StoreBankCard> storeBankCardQueryWrapper = new QueryWrapper<>();
        storeBankCardQueryWrapper.eq("store_id",storeId);
        storeBankCardQueryWrapper.eq("status",1);
        storeBankCardQueryWrapper.eq("bind",3);
        StoreBankCard storeBankCard = storeBankCardMapper.selectOne(storeBankCardQueryWrapper);
        if(storeBankCard==null){
            return null;
        }
        withdrawInfoVO.setBank(storeBankCard.getBank());
        int length = storeBankCard.getCardNo().length();
        withdrawInfoVO.setCardNo(storeBankCard.getCardNo().substring(length-4,length));
        withdrawInfoVO.setIcon(storeBankCard.getIcon());
        withdrawInfoVO.setName(storeBankCard.getName());
        withdrawInfoVO.setType(storeBankCard.getType());
        //获取可提现余额
        QueryWrapper<Store> storeQueryWrapper = new QueryWrapper<>();
        storeQueryWrapper.eq("store_id",storeId);
        Store store = storeMapper.selectOne(storeQueryWrapper);
        if(store==null){
            log.info(">>minjie 门店查询不存在");
            withdrawInfoVO.setBalance(0);
        }
        withdrawInfoVO.setBalance(store.getBalance());
        return withdrawInfoVO;
    }

    @Override
    public IPage<StoreVO> listbycondition(int page,int limit,String storeName,String agmName,String storePhone,
                                          String province,String city,String county,Integer professionId,String startTime, String endTime) {
        List<Long> storeIds = Lists.newArrayList();
        if(StringUtils.isNotEmpty(agmName)){//查询agm的店
            List<StoreStaff> storeStaffList = listStoreStaff(agmName);
            if(storeStaffList!=null && storeStaffList.size()>0){
                for(StoreStaff storeStaff:storeStaffList){
                    storeIds.add(storeStaff.getStoreId());
                }
            }
        }
        QueryWrapper<Store> storeQueryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(storeName))storeQueryWrapper.like("name",storeName);
        if(StringUtils.isNotEmpty(storePhone))storeQueryWrapper.like("store_phone",storePhone);
        if(StringUtils.isNotEmpty(province))storeQueryWrapper.like("province",province);
        if(StringUtils.isNotEmpty(city))storeQueryWrapper.like("city",city);
        if(StringUtils.isNotEmpty(county))storeQueryWrapper.like("county",county);
        if(storeIds!=null && storeIds.size()>0)storeQueryWrapper.in("store_id",storeIds);
        if(StringUtils.isNotEmpty(startTime))storeQueryWrapper.gt("ct",startTime);
        if(StringUtils.isNotEmpty(endTime))storeQueryWrapper.lt("ct",endTime);
        if(professionId!=null)storeQueryWrapper.last("AND FIND_IN_SET("+professionId+",profession_ids)");
        IPage<Store> storePage = storeMapper.selectPage(new Page<>(page,limit),storeQueryWrapper);
        PageResult<StoreVO> storeVOPageResult = new PageResult<>(storePage);
        List<StoreVO> storeVOList = Lists.newArrayList();
        if(storePage.getRecords()!=null && storePage.getRecords().size()>0){
            for(Store store:storePage.getRecords()){
                StoreVO storeVO = new StoreVO();
                storeVO.setStoreId(store.getStoreId());
                storeVO.setStoreName(store.getName());
                storeVO.setBrand(store.getBrand());
                storeVO.setAttribution(store.getProvince()+"-"+store.getCity()+"-"+store.getCounty());
                storeVO.setAddress(store.getAddress());
                storeVO.setStorePhone(store.getStorePhone());
                storeVO.setCt(store.getCt());
                storeVO.setStatus(store.getStatus());
                //查询agm
                StoreStaff storeStaff = selectStoreStaff(store.getStoreId().intValue());
                if(storeStaff!=null){
                    storeVO.setAgmName(storeStaff.getName());
                }
                //查询店铺类别
                int fristProfessionId = 0;
                if(StringUtils.isNotEmpty(store.getProfessionIds())){
                    fristProfessionId = Integer.valueOf(store.getProfessionIds().split(",")[0]);
                }
                StoreProfession storeProfession = selectProfession(fristProfessionId);
                if(storeProfession!=null)storeVO.setProfession(storeProfession.getName());
                storeVOList.add(storeVO);
            }
        }
        storeVOPageResult.setRecords(storeVOList);
        return storeVOPageResult;
    }

    /**
     * 查询店铺分类
     * @param profession_id
     * @return
     */
    private StoreProfession selectProfession(int profession_id){
        QueryWrapper<StoreProfession> storeProfessionQueryWrapper = new QueryWrapper<>();
        storeProfessionQueryWrapper.eq("profession_id",profession_id);
        StoreProfession storeProfession = storeProfessionMapper.selectOne(storeProfessionQueryWrapper);
        return storeProfession;
    }

    /**
     * 查询门店员工
     * @param storeId
     * @return
     */
    private StoreStaff selectStoreStaff(int storeId){
        QueryWrapper<StoreStaff> storeStaffQueryWrapper = new QueryWrapper<>();
        storeStaffQueryWrapper.eq("store_id",storeId);
        storeStaffQueryWrapper.eq("role_code",StoreConstants.STORE_STAFF_AGM);
        storeStaffQueryWrapper.last("LIMIT 1");
        StoreStaff storeStaff = storeStaffMapper.selectOne(storeStaffQueryWrapper);
        return storeStaff;
    }

    /**
     * 员工列表
     * @param agmName
     * @return
     */
    private List<StoreStaff> listStoreStaff(String agmName){
        QueryWrapper<StoreStaff> storeStaffQueryWrapper = new QueryWrapper<>();
        storeStaffQueryWrapper.eq("role_code",StoreConstants.STORE_STAFF_AGM);
        storeStaffQueryWrapper.like("name",agmName);
        List<StoreStaff> storeStaffList = storeStaffMapper.selectList(storeStaffQueryWrapper);
        return storeStaffList;
    }

}
